import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ValidationPipe } from '@nestjs/common';
import { join } from 'path';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  // 获取配置服务
  const configService = app.get(ConfigService);

  // 设置全局前缀
  app.setGlobalPrefix('api/v1');

  // 启用验证管道
  app.useGlobalPipes(new ValidationPipe({
    whitelist: true,
    forbidNonWhitelisted: true,
    transform: true,
    // 跳过未知/undefined 值的校验，避免自定义参数或无 body 情况触发 400
    forbidUnknownValues: false,
    skipUndefinedProperties: true,
  }));

  // 启用CORS
  app.enableCors({
    origin: true, // 开发环境允许所有来源
    credentials: true,
  });

  // 静态文件服务
  app.useStaticAssets(join(__dirname, '..', 'public'));

  // 配置Swagger文档
  const config = new DocumentBuilder()
    .setTitle('RWA Platform API')
    .setDescription('RWA (Real World Assets) Platform Backend API Documentation')
    .setVersion('1.0')
    .addTag('auth', 'Authentication endpoints')
    .addTag('users', 'User management endpoints')
    .addTag('kyc', 'KYC verification endpoints')
    .addTag('otc', 'OTC trading endpoints')
    .addTag('assets', 'Asset management endpoints')
    .addTag('applications', 'Application management endpoints')
    .addTag('blockchain', 'Blockchain interaction endpoints')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
        name: 'JWT',
        description: 'Enter JWT token',
        in: 'header',
      },
      'JWT-auth', // This name here is important for references
    )
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api/docs', app, document, {
    swaggerOptions: {
      persistAuthorization: true,
    },
    customSiteTitle: 'RWA Platform API Docs',
  });

  // 获取端口配置
  const port = configService.get('app.port') || 3000;

  await app.listen(port);
  console.log(`🚀 RWA Platform API is running on: http://localhost:${port}`);
  console.log(`📚 API Documentation available at: http://localhost:${port}/api/docs`);
}

bootstrap();
